﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WooCoo.ObjectModel.ManagedProperty
{
    /// <summary>
    /// 托管属性类中属性集，可对属性分类管理
    /// </summary>
    public class PropertyInfoSet
    {
        private List<IPropertyInfo> _Properties = new List<IPropertyInfo>(10);

        public PropertyInfoSet(Type ownerType)
        {
            this.OwnerType = ownerType;
        }

        /// <summary>
        /// 对应的类型
        /// </summary>
        public Type OwnerType { get; private set; }

        /// <summary>
        /// 当前类型声明的编译期属性
        /// </summary>
        /// <returns></returns>
        public IEnumerable<IPropertyInfo> GetProperties()
        {
            return this._Properties;
        }

        internal void AddProperty(IPropertyInfo property)
        {
            var index = this._Properties.BinarySearch(property, new PropertyComparer());
            if (index >= 0)
                throw new InvalidOperationException(string.Format("{0}属性已经注册", property.Name));
            property.Index = this._Properties.Count;
            // insert info at correct sorted index
            this._Properties.Insert(~index, property);
        }
    }

    internal class PropertyComparer : Comparer<IPropertyInfo>
    {
        public override int Compare(IPropertyInfo x, IPropertyInfo y)
        {
            return StringComparer.InvariantCulture.Compare(x.Name, y.Name);
        }
    }
}
